package com.suncaper.han_yi_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.suncaper.han_yi_system.mapper.MenuMapper;
import com.suncaper.han_yi_system.pojo.entity.LoginUser;
import com.suncaper.han_yi_system.pojo.entity.Menu;
import com.suncaper.han_yi_system.pojo.entity.User;
import com.suncaper.han_yi_system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws RuntimeException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(QueryWrapper);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //查询用户权限信息
        List<Menu> menus = menuMapper.findMenuByUserId(user.getId());
        List<String> authorities = menus.stream().map(Menu::getPermission).toList();

        return new LoginUser(user, authorities);
    }
}
